<?php
/**
 * Хелпер картинок
 * 
 * Хелпер картинок
 * @author Anton Zavidov
 * @package myLiveShop
 */

/**
 * Хелпер картинок
 *
 */
class HelperImage{
	/**
	 * информации про одну картинку по id
	 *
	 * @param int $image_id id картинки
	 * @return array
	 */
	private $model = false;
	function __construct(){
		$this->model = import('model.image',true);
	}
	public function get($image_id){
	    $data = $this->model->loadOne($image_id);
	    if(!File::exists('data/origin/'.$data['filename'])) return false;
	    return $data;
	}
	public function getForElement($model, $model_id){
	    $data = $this->model->load(false,array(
	    	ModelImage::F_IMAGE_ID, 
	    	ModelImage::F_FILENAME,
	    	ModelImage::F_FILE,
	    	ModelImage::F_SIZE
	    	),array(
			'where'=>ModelImage::F_MODEL.'="'.$model.'" AND '.ModelImage::F_MODEL_ID.'='.$model_id
			)
		);
		foreach ($data as &$item) {
			if(!File::exists('data/origin/'.$item['filename'])) unset($item);
		}
	    return $data;
	}
	public function setModule($image_id, $model, $model_id){
		$this->model->save(array(
    		ModelImage::F_MODEL => $model,
    		ModelImage::F_MODEL_ID => $model_id
    	),$image_id);
	}
	public function eraseFromModule($model, $model_id){
		$this->model->save(array(
    		ModelImage::F_MODEL => 'tmp',
    		ModelImage::F_MODEL_ID => 0
    	),false,array('where'=>ModelImage::F_MODEL.'="'.$model.'" AND '.ModelImage::F_MODEL_ID.'="'.$model_id.'"'));
	}
	public function deleteImageFromModule($model, $model_id, $deleteFromBase = true){
		$filename = $this->model->loadOne(false,array(ModelImage::F_IMAGE_ID, ModelImage::F_FILENAME),array(
			'where'=>ModelImage::F_MODEL.'="'.$model.'" AND '.ModelImage::F_MODEL_ID.'='.$model_id
			)
		);
		if($deleteFromBase) $this->model->delete($filename[ModelImage::F_IMAGE_ID]);
		return $this->deleteImageFile($filename[ModelImage::F_FILENAME]);
	}
	public function deleteImageById($image_id, $deleteFromBase = true){
		if(!$image_id) return true;
		$filename = $this->model->loadOne($image_id,array(ModelImage::F_IMAGE_ID, ModelImage::F_FILENAME));
		if($deleteFromBase) $this->model->delete($filename[ModelImage::F_IMAGE_ID]);
		return $this->deleteImageFile($filename[ModelImage::F_FILENAME]);
	}
	private function deleteImageFile($file){
		if(!$file) return true;
		if(!File::delete('data/origin/'.$file)) return false;
		return true;
	}
}